package ru.surfstudio.graduate.parser;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Locale;

import org.json.JSONArray;
import org.json.JSONObject;

import ru.surfstudio.graduate.data.Feed;
import ru.surfstudio.graduate.exception.ParseException;

public class FeedSearchParser extends Parser<ArrayList<Feed>> {

	private static final long serialVersionUID = 1L;

	private static final String TAG = "FeedSearchParser";
	
	private static final String RESPONSE_DATA = "responseData";
	
	private static final String FEED = "feed";
	
	private static final String ENTRIES = "entries";
	
	private static final String TITLE = "title";
	
	private static final String LINK = "link";
	
	private static final String CONTENT = "content";
	
	private static final String AUTHOR = "author";
	
	private static final String PUBLISHED_DATE = "publishedDate";
	private static final String DATE_FORMAT = "EEE, dd MMM yyyy HH:mm:ss Z";

	@Override
	public ArrayList<Feed> parse(String responseString) throws ParseException {
		try {
			ArrayList<Feed> feedList = new ArrayList<Feed>();
			
			JSONObject response = new JSONObject(responseString);
			JSONObject responseData = response.getJSONObject(RESPONSE_DATA);
			JSONObject feedObj = responseData.getJSONObject(FEED);
			JSONArray entries = feedObj.getJSONArray(ENTRIES);
			for (int i = 0; i < entries.length(); i++) {
				JSONObject entry = entries.getJSONObject(i);
				
				Feed feed = new Feed();
				feed.setName(entry.getString(TITLE));
				feed.setUrl(entry.getString(LINK));
				feed.setContent(entry.getString(CONTENT));
				feed.setAuthor(entry.getString(AUTHOR));
				feed.setDate(formatDate(entry.getString(PUBLISHED_DATE)));
				feedList.add(feed);
			}
			return feedList;
			
		} catch (Exception e) {
			throw new ParseException(e.getMessage(), e);
		}
	}
	
	public Date formatDate(String str) throws java.text.ParseException {
		
		SimpleDateFormat format = new SimpleDateFormat(DATE_FORMAT, Locale.US);
		return format.parse(str);
	}
	

}
